package com.glasses.primework;

import java.io.File;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletContext;
import org.primefaces.model.CroppedImage;

@ManagedBean
public class ImageCropperBean {
    private CroppedImage image;
    private CroppedImage croppedImage;
    private String newImageName;
    
    public CroppedImage getImage() {
        System.out.println("ImageCropperBean gave its image!");
        return image;
    }
    
    public void setImage(CroppedImage image) {
        System.out.println("ImageCropperBean got new image!");
        this.image = image;
    }
    
    public CroppedImage getCroppedImage() {
        System.out.println("ImageCropperBean gave its cropped image!");
        return croppedImage;
    }
    
    public void setCroppedImage(CroppedImage image) {
        System.out.println("ImageCropperBean got new cropped image!");
        this.croppedImage = image;
    }
    
    public String getNewImageName() {
        System.out.println("getNewImageName() = " + newImageName);
        return newImageName;
    }
    
    public void setNewImageName(String newImageName) {
        this.newImageName = newImageName;
    }
    
    private String getRandomImageName() {
        int i = (int) (Math.random() * 100000);
         
        return String.valueOf(i);
    }
    
    public void crop() {
        if(croppedImage == null) {
            return;
        }
        
        setNewImageName(getRandomImageName());
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        String newFileName = servletContext.getRealPath("") + 
                             File.separator + "IMG" + 
                             File.separator + "crop" + 
                             File.separator + getNewImageName() + ".jpg";
        
        FileImageOutputStream imageOutput;
        try {
            System.out.println("File to be written to: " + newFileName + "...");
            imageOutput = new FileImageOutputStream(new File(newFileName));
            System.out.println("... instance created ...");
            imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
            System.out.println("... written ...");
            imageOutput.close();
            System.out.println("... done!");
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Cropping failed."));
            System.out.println("... failed!");
        }
         
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "Cropping finished."));
    }
}
